import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'

import toNative from '@/utils/toNative'

import Dialog from '@/components/dialog/Index'

import type { ComponentPublicInstance } from 'vue'
import { getNeedSyncInvoiceList } from '@/api/invoice'
import {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import { Button, Card, Checkbox, Input, message } from 'ant-design-vue'
import { CloseOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { getInsureIndustryList } from '@/api/insureIndustry'
import type { InsureIndustryListDto, InsureOccupationDto } from '@/api/insureIndustry/types'
import type { CheckboxChangeEvent } from 'ant-design-vue/es/checkbox/interface'
import { getInsurePeriodServeCompanyDetail } from '@/api/insurance/serveCompany'
import { OccupationAuditStatusCnEnum } from '@/const/enum'
import { auditOccupation } from '@/api/occupationAudit'
import { shake } from '@/utils/util'

@Component
export class DialogRecharge extends Render {
    @Prop({ default: false }) show!: boolean
    @Prop() id!: number
    @Prop() periodServeCompanyId!: number

    specialAppoint = ''

    showDialog = false

    industryList = [] as InsureIndustryListDto[] // 行业列表
    occupationList = [] as InsureOccupationDto[] // 工种列表
    selectedList = [] as InsureOccupationDto[] // 选中的工种列表

    showIndex = 0

    @Emit('update:show')
    emitShow(val: boolean) {
        return val
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('show', { immediate: true })
    async handleWatchShow() {
        this.showDialog = this.show
        if (this.show) {
            this.basicForm = renderForm(this.basicFormConfig)
            this.initList()
            this.initSpecialAppoint()
        }
    }

    @Watch('showDialog', { immediate: true })
    handleWatchDialogShow() {
        this.emitShow(this.showDialog)
    }

    basicFormConfig = this.initBasicFormConfig() as FormModalDto
    initBasicFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            noPadding: true,
            items: {
                name: {
                    name: '',
                    element: 'input',
                    params: {
                        prepend: <SearchOutlined />
                    },
                    callback: {
                        change: () => {
                            shake(() => {
                                this.initList()
                            })
                        }
                    }
                }
            },
            complete: async () => {},
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {
                initModelValue(this.basicFormConfig)
            }
        } as FormModalDto
    }

    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    clear() {}

    // 获取特别约定
    async initSpecialAppoint() {
        const res = await getInsurePeriodServeCompanyDetail(this.periodServeCompanyId)
        this.specialAppoint = res?.specialAppoint
    }

    // 获取行业列表
    async initList() {
        const data = getModelValue(this.basicFormConfig)
        const res = await getInsureIndustryList({
            ...data
        })
        this.industryList = res
        if (this.industryList?.length) {
            this.occupationList = this.industryList[0].occupationList
        }
    }

    onChange(item: InsureIndustryListDto, index: number) {
        this.showIndex = index
        this.occupationList = item.occupationList
    }

    onCheckboxChange(event: CheckboxChangeEvent, item: InsureOccupationDto, index: number) {
        const checked = event.target.checked
        if (checked) {
            this.selectedList.push(item)
        } else {
            const index = this.selectedList.findIndex((i) => i.id === item.id)
            if (index !== -1) {
                this.selectedList.splice(index, 1)
            }
        }
    }

    onRemove(item: InsureOccupationDto) {
        const index = this.selectedList.findIndex((i) => i.id === item.id)
        if (index !== -1) {
            this.selectedList.splice(index, 1)
        }
    }

    onCancel() {
        this.showDialog = false
    }

    async onConfirm() {
        if (!this.selectedList?.length) {
            message.warn('请选择工种')
            return
        }
        const params = {
            id: this.id,
            specialAppoint: this.specialAppoint,
            auditStatus: OccupationAuditStatusCnEnum.审核通过,
            occupationIds: this.selectedList.map((i) => i.id)
        }
        await auditOccupation(params)
        this.showDialog = false
        this.handleRefresh()
    }

    render(data: ComponentPublicInstance) {
        return (
            <>
                <Dialog
                    v-model:show={this.showDialog}
                    title="工种审核"
                    width={1100}
                    v-slots={{
                        default: () => {
                            return (
                                <>
                                    <div class="flex items-center mb-20px">
                                        <span class="flex-shrink-0 mr-10px">特别约定</span>
                                        <Input v-model:value={this.specialAppoint}></Input>
                                    </div>
                                    <div class="flex gap-x-20px">
                                        <Card class="flex-3">
                                            <div>{this.basicForm.element()}</div>
                                            <div class="flex gap-x-20px">
                                                <div class="flex-2 max-h-300px overflow-auto">
                                                    {this.industryList.map((item, index) => {
                                                        return (
                                                            <div
                                                                onClick={() =>
                                                                    this.onChange(item, index)
                                                                }
                                                                class={`text-black-200 cursor-pointer py-6px cursor-pointer border-l-2 border-l-white border-l-solid pl-10px ${this.showIndex === index ? '!border-l-blue-100 bg-blue-300' : ''}`}
                                                            >
                                                                {item.name}
                                                            </div>
                                                        )
                                                    })}
                                                </div>
                                                <div class="flex-3 max-h-300px overflow-auto">
                                                    {this.occupationList.map((item, index) => {
                                                        return (
                                                            <div class="py-6px">
                                                                <Checkbox
                                                                    checked={this.selectedList.some(
                                                                        (i) => i.id === item.id
                                                                    )}
                                                                    onChange={(event) =>
                                                                        this.onCheckboxChange(
                                                                            event,
                                                                            item,
                                                                            index
                                                                        )
                                                                    }
                                                                >
                                                                    <div class="text-black-200">
                                                                        <span>{item.name}</span>
                                                                        <span>（{item.level}类）</span>
                                                                        <span>{item.id}</span>
                                                                    </div>
                                                                </Checkbox>
                                                            </div>
                                                        )
                                                    })}
                                                </div>
                                            </div>
                                        </Card>
                                        <Card class="flex-2">
                                            <div>已选中{this.selectedList.length}项</div>
                                            <div class="max-h-350px overflow-auto">
                                                {this.selectedList.map((item, index) => {
                                                    return (
                                                        <div class="flex justify-between py-6px text-black-200">
                                                            <div>
                                                                <span>{item.name}</span>
                                                                <span>（{item.level}类）</span>
                                                                <span>{item.id}</span>
                                                            </div>
                                                            <div
                                                                class="cursor-pointer"
                                                                onClick={() => this.onRemove(item)}
                                                            >
                                                                <CloseOutlined />
                                                            </div>
                                                        </div>
                                                    )
                                                })}
                                            </div>
                                        </Card>
                                    </div>
                                </>
                            )
                        },
                        footer: () => {
                            return (
                                <div class="flex justify-center">
                                    <Button type="primary" onClick={this.onConfirm}>
                                    确定
                                    </Button>
                                </div>
                            )
                        }
                    }}
                ></Dialog>
            </>

        )
    }
}

export default toNative<{ id: number; periodServeCompanyId: number }, { refresh: () => void }>(
    DialogRecharge
)
